package com.ruoyi.patient.utils;

import com.alibaba.druid.support.json.JSONUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.Map.Entry;

public class SignGenerator {
	static Map<String, Object> tokenMap = new HashMap<String, Object>();

	/**
	 * @Function buildSign
	 * @author zzy
	 * @todo 互联网平台签名
	 * @param map
	 * @param security
	 * @param encodeType
	 * @return
	 * @return String
	 * @date 2021年3月4日 下午5:55:17
	 */
	public static void 	buildSign(Map<String, Object> map, String security, String encodeType) {
    	Map<String, Object> signMap = new HashMap<String, Object>();
    	signMap.putAll(map);
    	HashMap<String, Object> biz = (HashMap<String, Object>) signMap.get("biz_content");
    	for (String key :biz.keySet()) {
			String value = null;
			if (biz.get(key) instanceof String) {
				value = (String) biz.get(key);
			} else {
				value = JSONUtils.toJSONString(biz.get(key));
			}
			signMap.put(key, value);
		}
    	signMap.remove("biz_content");
    	if ("MD5".equals(encodeType)) {
			List<Entry<String, Object>> params = sortMap(signMap);
			StringBuilder sign = new StringBuilder();
			for (int i = 0; i < params.size(); i++) {
				if (!StringUtils.isEmpty(sign.toString())) {
					sign.append("&");
				}
				sign.append(params.get(i).getKey()).append("=").append(params.get(i).getValue());
			}

			sign.append(security);
			//System.out.println("sign=====" + sign.toString());

			String md5Str = MD5Util.md5(sign.toString()).toUpperCase();;
	        map.put("sign", md5Str);
		}

	}

    public static List<Entry<String, Object>> sortMap(final Map<String, Object> map) {
        final List<Entry<String, Object>> infos = new ArrayList<Entry<String, Object>>(map.entrySet());

        // 重写集合的排序方法：按字母顺序
        Collections.sort(infos, new Comparator<Entry<String, Object>>() {
            @Override
            public int compare(final Entry<String, Object> o1, final Entry<String, Object> o2) {
                return (o1.getKey().toString().compareTo(o2.getKey()));
            }
        });

        return infos;
    }

    /**
     * @Function buildSignJzUser
     * @author zzy
     * @todo 庆阳sign
     * @param map
     * @param encodeType
     * @return void
     * @date 2021年9月27日 下午4:40:27
     */
    public static void buildSignJzUser(Map<String, Object> map, String encodeType) {
    	Map<String, Object> signMap = new HashMap<String, Object>();
    	signMap.putAll(map);

    	if ("MD5".equals(encodeType)) {
			List<Entry<String, Object>> params = sortMap(signMap);
			StringBuilder sign = new StringBuilder();
			for (int i = 0; i < params.size(); i++) {
				if (!StringUtils.isEmpty(sign.toString())) {
					sign.append("&");
				}
				sign.append(params.get(i).getKey()).append("=").append(params.get(i).getValue());
			}

//			sign.append("&secret=").append(BizMethodConstant.ENCRYPTKEY);

	        String md5Str = MD5Util.md5(sign.toString()).toUpperCase();
	        if (md5Str.length() < 32) {
				int qnum = 32 - md5Str.length();
				md5Str = String.format("%0" + qnum + "d", 0) + md5Str;
			}
            try {
				MessageDigest md = MessageDigest.getInstance("MD5");
				byte[] digest = md.digest(md5Str.getBytes(StandardCharsets.UTF_8));
				map.put("X-Ca-Signature", Base64.getEncoder().encodeToString(digest));
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }

		}
	}

	/**
	 * 互联网平台签名
	 * @param map
	 * @param encodeType
	 */
    public static void buildSignPt(Map<String, Object> map, String encodeType) {
    	Map<String, Object> signMap = new HashMap<String, Object>();
    	signMap.putAll(map);

    	if ("MD5".equals(encodeType)) {
			List<Entry<String, Object>> params = sortMap(signMap);
			StringBuilder sign = new StringBuilder();
			for (int i = 0; i < params.size(); i++) {
				if (!StringUtils.isEmpty(sign.toString())) {
					sign.append("&");
				}
				sign.append(params.get(i).getKey()).append("=").append(params.get(i).getValue());
			}

//			sign.append("&secret=").append(BizMethodConstant.ENCRYPTKEY);

	        String md5Str = MD5Util.md5(sign.toString()).toUpperCase();
	        if (md5Str.length() < 32) {
				int qnum = 32 - md5Str.length();
				md5Str = String.format("%0" + qnum + "d", 0) + md5Str;
			}
            try {
				MessageDigest md = MessageDigest.getInstance("MD5");
				byte[] digest = md.digest(md5Str.getBytes(StandardCharsets.UTF_8));
				map.put("sign", Base64.getEncoder().encodeToString(digest));
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }

		}
	}

	public static void main(String[] args) {
//		Appraise appraise = new Appraise();
//		appraise.setUnifiedOrgCode("370898789876746557");
//		appraise.setScoring(1);
//		appraise.setEvaluationDatetime(new Date());
//		appraise.setBusinessCode("2501.01");
//		appraise.setBusinessCode2("0");
//		appraise.setBusinessTypeCode("1");
//		appraise.setEvaluations("1");
//		appraise.setIdcardNo("1");
//		appraise.setIdcardTypeCode("2");
//
//		String data = JSONUtils.toJSONString(MapUtil.objetToMap(appraise));
//
//		Map<String, Object> params = MapUtil.buildMap(data, ConstantUtil.APPRAISE, "Body", "bizApp");
//		if (params == null) {
//			System.out.println("获取token失败");
//		}
//
//		String results = HttpClientUtil.post(ConstantUtil.BASE_WEB_URL, JSONUtils.toJSONString(params));
//		System.out.println(results);
//		Map<String, Object> params = new HashMap<String, Object>();
//		params.put("FUN_CODE", "2014");
//		params.put("USER_ID", "50010");
//		params.put("REQ_ENCRYPTED", "333");
//		buildSignJzUser(params, "MD5");
//       System.out.println(params.get("SIGN"));
		System.out.println(String.format("%0" + 2 + "d", 0) + "34fefge");
	}

}
